import Foundation
import AVFoundation

protocol AudioPCMPlayerDelegate: AnyObject {
    func player(_ player: AudioSpectrumPlayer, didGeneratePCMData data: [Float])
    func playCompleted(_ player: AudioSpectrumPlayer) // 新增播放完成回调

}

class AudioSpectrumPlayer {
    
    weak var delegate: AudioPCMPlayerDelegate?
    private let engine = AVAudioEngine()
    private let player = AVAudioPlayerNode()
    
    public var bufferSize: Int? {
        didSet {
            if let bufferSize = self.bufferSize {
                engine.mainMixerNode.removeTap(onBus: 0)
                engine.mainMixerNode.installTap(onBus: 0, bufferSize: AVAudioFrameCount(bufferSize), format: nil)
                { [weak self] buffer, when in
                    guard let strongSelf = self else { return }
                    if !strongSelf.player.isPlaying { return }
                    buffer.frameLength = AVAudioFrameCount(bufferSize)
                    
                    // 提取原始PCM数据
                    guard let floatChannelData = buffer.floatChannelData else { return }
                    let channelCount = Int(buffer.format.channelCount)
                    let frameLength = Int(buffer.frameLength)
                    
                    var pcmData = [Float]()
                    
                    if buffer.format.isInterleaved {
                        // 解交错处理（多声道交织）
                        for i in stride(from: 0, to: frameLength * channelCount, by: channelCount) {
                            pcmData.append(floatChannelData.pointee[i])
                        }
                    } else {
                        // 非交错数据（单声道连续）
                        pcmData = Array(UnsafeBufferPointer(
                            start: floatChannelData.pointee,
                            count: frameLength
                        ))
                    }
                    
                    // 回调传递数据
                    DispatchQueue.main.async {
                        strongSelf.delegate?.player(strongSelf, didGeneratePCMData: pcmData)
                    }
                }
            }
        }
    }
    
    init(bufferSize: Int = 2048) {
        engine.attach(player)
        engine.connect(player, to: engine.mainMixerNode, format: nil)
        engine.prepare()
        try! engine.start()
    
        defer {
            self.bufferSize = bufferSize
        }
    }

    func play(withFilePath filePath: String) {
        let audioFileURL = URL(fileURLWithPath: filePath)
            
            do {
                let audioFile = try AVAudioFile(forReading: audioFileURL)
                player.stop()
                
                // 添加引擎启动（如果使用AVAudioEngine）
                if let engine = player.engine, !engine.isRunning {
                    try engine.start()
                }
                
                player.scheduleFile(audioFile, at: nil) { [weak self] in
                                DispatchQueue.main.async {
                                    guard let self = self else { return }
                                    self.delegate?.playCompleted(self)
                                }
                            }
                player.play()
            } catch {
                print("播放失败：\(error.localizedDescription)")
            }
    }
    
    func stop() {
        player.stop()
    }
}
